#include "DetailQuoteTable.h"
#include "BondDetailData.h"
#include "../BondUtility.h"
#include "../GridImage.h"
#include "../StringResource.h"
#include <widgets/table/STable.h>
#include <widgets/table/STableColumnSet.h>
#include <widgets/STabCtrl.h>
#include <qbtools/tools.h>
#include <uam/UserAccountManager.h>
#include <core/StyleMgr.h>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QButtonGroup>
#include <QComboBox>
#include <QHeaderView>
#include <QStandardItemModel>
#include <QTableView>
#include <QStylePainter>
#include "../BondColDelegate.h"
//#include "ui_DetailQuoteTableBase.h"

DetailQuoteTable::DetailQuoteTable(QWidget* p, QSharedPointer<DetailData> d, int type)
    : QFrame(p),m_data(d), m_type(type)
{

	QVBoxLayout* l = new QVBoxLayout(this);
	l->setContentsMargins(4, 4, 4, 0);
	l->setSpacing(4);
    /*
	QHBoxLayout* titleL = new QHBoxLayout();
	titleL->setContentsMargins(0, 0, 0, 0);
	titleL->setSpacing(0);
	l->addLayout(titleL);

	m_tab = new STabCtrl(this);
	m_tab->addTab(tr("逐笔"), m_data->hasMktStreamRight() ? "" : tr("成为正式会员即可查看"));
	m_tab->addTab(tr("今日成交"));
	m_tab->setFixedSize(72 * 2, 24);

	titleL->addStretch();
	titleL->addWidget(m_tab);
	titleL->addStretch();
    if (m_type == DETAILOTHERTYPE_BROKER){
    }*/
		

	m_table = new SVirtualTable(this);
	m_model = new DefaultTableModel(this);
	m_model->setTable(m_table);
	
	
	m_table->table()->setModel(m_model);
	m_table->table()->horizontalHeader()->hide();
    l->addWidget(m_table, 1);
	initCols();

	if (!m_data->hasMktStreamRight())
	{
        //m_tab->setTabDisabled(0);
        //m_tab->selectTab(1);
		setFilterType(data_tkn);
	}
    //else
        //m_tab->selectTab(0);

	connect(m_table, &SVirtualTable::viewPosChanged, this, &DetailQuoteTable::onTableViewPosChagned);

	if (m_type == DETAILOTHERTYPE_BROKER)
	{
        connect(m_data.get(), &DetailData::marketStreamChanged, this, &DetailQuoteTable::onMarketStreamDataChanged);
        connect(m_data.get(), &DetailData::mktStreamDealChanged, this, &DetailQuoteTable::onMktStreamDealDataChanged);
        connect(m_data.get(), &DetailData::hisPriceChanged, this, QOverload<>::of(&QWidget::update));
	}
	else if (m_type == DETAILOTHERTYPE_CFETS)
	{
        connect(m_data.get(), &DetailData::cfetsMarketStreamChanged, this, &DetailQuoteTable::onMarketStreamDataChanged);
        connect(m_data.get(), &DetailData::mktStreamDealCfetsChanged, this, &DetailQuoteTable::onMktStreamDealDataChanged);
	}

    connect(m_data.get(), &DetailData::clearSpeedChanged, this, &DetailQuoteTable::updateDataView);
    //connect(m_tab, &STabCtrl::tabSelected, this, &DetailQuoteTable::onTabClicked);
    connect(m_data.get(), &DetailData::bondChanged, this, &DetailQuoteTable::updateDataView);
	QString style = QString("DetailQuoteTable {background-color:#%1;border:none;border-radius:2px;}").arg(StyleMgr::instance().color("BasicPlate").rgb(), 0, 16);
	setStyleSheet(style);
}

void DetailQuoteTable::setFilterType(kDataType t)
{
	if (m_filterType == t)
		return;
	m_filterType = t;

	updateDataView();
}

void DetailQuoteTable::onTableViewPosChagned(int pos)
{
	updateTable();
}

void DetailQuoteTable::onMarketStreamDataChanged(QList<int> ids)
{
	updateDataView();
	for (auto id : ids)
	{
		m_table->addFlashInfo({ QString::number(id)});
	}
}

void DetailQuoteTable::onMktStreamDealDataChanged(QList<QString> ids)
{
	updateDataView();
	for (auto id : ids)
	{
		m_table->addFlashInfo({ id });
	}
}

void DetailQuoteTable::updateDataView()
{
	updateDisplayMktStream();
	m_table->setRealDataCount(m_mktStream.size());
	updateTable();

}

void DetailQuoteTable::onTabClicked(int index, bool toggled)
{
    if (toggled) {
        if (index == 0)
            setFilterType(data_all);
        else
            setFilterType(data_tkn);
    }
}

void DetailQuoteTable::updateTable()
{
	m_table->clearTable();
	m_model->setRowCount(m_table->pageCount());

	int nValue = atoi(SSUserAccountManager::instance().GetPermission().GetValue(USER_PERMISSION_QB_PRO));
	bool showBroker = nValue == 1 || nValue == 2;

	QFont f = font();
	f.setPixelSize(13);
	f.setBold(true);

	QFont timeF = f;
	timeF.setPixelSize(12);

	int pos = m_table->sliderPos();
	for (int row = 0; row < m_table->pageCount() && row + pos < (int)m_mktStream.size(); ++row)
	{
		const xQBMarketStreamUnit_c& marketInfo = m_mktStream[row + pos];
		int nMsgType = atoi(marketInfo.m_type);
		int nType = BondUtility::makeTypeOperate(nMsgType, atoi(marketInfo.m_operate));
		bool bCancel = false;
		if (nType != change && nType != -1 && atoi(marketInfo.m_body2.m_dealStatus) == 8)
			bCancel = true;

		for (int col = 0; col < m_cols.size(); ++col)
		{
			int colType = m_cols[col];
			QStandardItem* item = m_model->item(row, col);
			if (item == nullptr)
				item = new QStandardItem();
			item->clearData();
			item->setData(StyleMgr::instance().color("Highlight"), Qt::ForegroundRole);
			item->setData((int)(Qt::AlignLeft | Qt::AlignVCenter), Qt::TextAlignmentRole);
			item->setData(StyleMgr::instance().color("BasicPlate"), Qt::BackgroundRole);

			item->setFont(f);

			if (colType == col_PrcOther_State)//state
			{
				item->setData(BondUtility::gridImage((EnumImgFlag)nType), Qt::DecorationRole);
			}
			else if (colType == col_PrcOther_BuyVol)//买量
			{
				item->setData((int)(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole);
				if (nType == change)
				{
					QString volumn;
					if (nMsgType == 1)
						volumn = QString::fromLocal8Bit(nMsgType == 1 ? marketInfo.m_body1.m_bidvolume : marketInfo.m_body2.m_volume);

					QString itemValue = "--";
					if (!volumn.isEmpty() && volumn != "0")
					{
						if (strcmp(marketInfo.m_company_id, "e") == 0)
						{
							itemValue = volumn;
						}
						else
						{
							itemValue = SSTools::StringRemoveZero(volumn, m_type == DETAILOTHERTYPE_BROKER);
						}
					}
					item->setData(itemValue, Qt::DisplayRole);
				}
				/* TODO:
				else if (m_nType == DETAILOTHERTYPE_EXCHANGE)
				{
					//Item.strText = SSA2W(marketInfo.m_body2.m_volume);
					if (m_matchVisible) {
						//展示类型
						Item.strText = NewStringTable.strExchangeDealMode(atoi((marketInfo.m_body2.m_tradeMode)));
					}
				}
				*/
			}
			else if (colType == col_PrcOther_Buy)//买价
			{
				item->setData((int)(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole);

				QString bidPrice;
				QString bidOfrId;
				int imgIndex = -1;
				if (nMsgType == 1)
				{
					if (m_type == DETAILOTHERTYPE_EXCHANGE && BondUtility::isTransBond(m_data->bond()))
					{
						bidPrice = QString::fromLocal8Bit(marketInfo.m_body1.m_bid_cleanprice);
					}
					else
					{
						bidPrice = QString::fromLocal8Bit(marketInfo.m_body1.m_bidprice);
						bidOfrId = QString::fromLocal8Bit(marketInfo.m_body1.m_bidOfferId);
					}

					if (bidOfrId.isEmpty() || bidPrice.isEmpty())
					{
						bidPrice = "--";
					}
					else if (bidPrice == "Bid" || (!bidOfrId.isEmpty() && bidPrice.isEmpty()))
					{
						bidPrice = "Bid";
					}
					else
					{
						QString strTemp;
						BondUtility::translateDonePrice(bidPrice, strTemp);
						bidPrice = strTemp;
					}

					item->setData(bidPrice, Qt::DisplayRole);
					if (!bidPrice.isEmpty() && bidPrice != "Bid")
					{
						if (marketInfo.m_body1.IsBidCleanPrice())
						{
							imgIndex = OTHER_PIG_CLEAN_SOURTH;
							item->setData(NewStringTable::strClean(), Qt::ToolTipRole);
						}
						else if (marketInfo.m_body1.IsBidFullPrice())
						{
							imgIndex = OTHER_PIG_FULL_SOURTH;
							item->setData(NewStringTable::strFull(), Qt::ToolTipRole);
						}
					}
				}
				else if (nMsgType == 2)
				{
					if (m_type == DETAILOTHERTYPE_EXCHANGE)
					{
						if (!BondUtility::isTransBond(m_data->bond()))
							bidPrice = QString::fromLocal8Bit(marketInfo.m_body2.m_yield);
					}
					else
					{
						bidPrice = QString::fromLocal8Bit(marketInfo.m_body2.m_price);
					}

					QString displayTxt = "--";
					if (!bidPrice.isEmpty())
					{
						BondUtility::translateDonePrice(bidPrice, displayTxt);
					}
					if (bCancel)
					{
						item->setData(BondUtility::gridImage((EnumImgFlag)grid_bid_cancel), Qt::DecorationRole);
					}

					item->setData(displayTxt, Qt::DisplayRole);

					if (displayTxt != "--")
					{
						if (marketInfo.m_body2.IsCleanPrice())
						{
							imgIndex = OTHER_PIG_CLEAN_SOURTH;
							item->setData(NewStringTable::strClean(), Qt::ToolTipRole);
						}
						else if (marketInfo.m_body2.IsFullPrice())
						{
							imgIndex = OTHER_PIG_FULL_SOURTH;
							item->setData(NewStringTable::strFull(), Qt::ToolTipRole);
						}
					}
				}
				if (!bCancel)
				{
					bool bBroker = strlen(marketInfo.m_company_id) > 0 && CBrokerList::IsValidBroker(atoi(marketInfo.m_company_id));
					if (imgIndex != -1 && bBroker)
					{
						item->setData(BondUtility::gridImage((EnumImgFlag)OTHER_PIG_CLEAN_SOURTH), Qt::DecorationRole);
					}
				}

				if (nType == change)
					item->setData(StyleMgr::instance().color("Bid_GVN_H1"), Qt::ForegroundRole);
			}
			else if (colType == col_PrcOther_Sale)//卖价
			{
				item->setData((int)(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole);
				item->setData(StyleMgr::instance().color("Ofr_TKN_H1"), Qt::ForegroundRole);

				QString ofrPrice;
				QString ofrOfrId;
				QString displayTxt;
				int imgIndex = -1;
				if (nMsgType == 1)
				{
					if (m_type == DETAILOTHERTYPE_EXCHANGE && BondUtility::isTransBond(m_data->bond()))
					{
						ofrPrice = QString::fromLocal8Bit(marketInfo.m_body1.m_ofr_cleanprice);
					}
					else
					{
						ofrPrice = QString::fromLocal8Bit(marketInfo.m_body1.m_ofrprice);
						ofrOfrId = QString::fromLocal8Bit(marketInfo.m_body1.m_ofrOfferId);
					}
					if (ofrOfrId.isEmpty() && ofrPrice.isEmpty())
					{
						displayTxt = "--";
					}
					else if (ofrPrice == "Ofr" || (!ofrOfrId.isEmpty() && ofrPrice.isEmpty()))
					{
						displayTxt = "Ofr";
					}
					else
					{
						BondUtility::translateDonePrice(ofrPrice, displayTxt);
					}

					if (displayTxt != "--" && ofrPrice != "Ofr")
					{
						if (marketInfo.m_body1.IsOfrCleanPrice())
						{
							imgIndex = OTHER_PIG_CLEAN_SOURTH;  //净价
							item->setData(NewStringTable::strClean(), Qt::ToolTipRole);
						}
						else if (marketInfo.m_body1.IsOfrFullPrice())
						{
							imgIndex = OTHER_PIG_FULL_SOURTH;  //全价
							item->setData(NewStringTable::strFull(), Qt::ToolTipRole);
						}
					}
				}
				else if (m_type == DETAILOTHERTYPE_EXCHANGE)
				{
					ofrPrice = QString::fromLocal8Bit(marketInfo.m_body2.m_cleanPrice);
					BondUtility::translateDonePrice(ofrPrice, displayTxt);
				}

				item->setData(displayTxt, Qt::DisplayRole);
				if (!bCancel)
				{
					bool bBroker = strlen(marketInfo.m_company_id) > 0 && CBrokerList::IsValidBroker(atoi(marketInfo.m_company_id));
					if (imgIndex != -1 && bBroker)
					{
						item->setData(BondUtility::gridImage((EnumImgFlag)OTHER_PIG_CLEAN_SOURTH), Qt::DecorationRole);
					}
				}
			}
			else if (colType == col_PrcOther_SaleVol)//卖量
			{
				item->setData((int)(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole);
				QString volume;
				QString displayTxt;
				if (nMsgType == 1)
					volume = QString::fromLocal8Bit(marketInfo.m_body1.m_ofrvolume);
				else if (nMsgType == 2)
					volume = QString::fromLocal8Bit(marketInfo.m_body2.m_volume);

				if (nType == change)
				{
					displayTxt = "--";
					if (!volume.isEmpty() && volume != "0")
					{
						if (strcmp(marketInfo.m_company_id, "e") != 0)
							displayTxt = SSTools::StringRemoveZero(volume, m_type == DETAILOTHERTYPE_BROKER);
					}
				}
				else if (m_type == DETAILOTHERTYPE_EXCHANGE)
				{
					//根据产品经理要求，统一移动这列
					displayTxt = QString::fromLocal8Bit(marketInfo.m_body2.m_volume);
				}
				else if (showBroker)
				{
					int nCuBroker = atoi(marketInfo.m_company_id);
					if (CBrokerList::IsValidBroker(nCuBroker)) {
						int nImg = -1;
						if (nCuBroker == 98)
							nImg = 27;
						else
							nImg = nCuBroker + 20;

						item->setData(BondUtility::gridImage((EnumImgFlag)nImg), Qt::DecorationRole);
					}
				}

				item->setData(displayTxt, Qt::DisplayRole);
			}
			else if (colType == col_PrcOther_Update)
			{
				item->setData((int)(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole);
				time_t lastTime = qMax(marketInfo.m_create_time, marketInfo.m_modify_time);
				tm* pTime = localtime(&lastTime);

				if (pTime != NULL && lastTime > 0)
					item->setData(QString("%1:%2:%3").arg(pTime->tm_hour, 2, 10, QChar('0'))
						.arg(pTime->tm_min, 2, 10, QChar('0')).
						arg(pTime->tm_sec, 2, 10, QChar('0')), Qt::DisplayRole);

				item->setData(StyleMgr::instance().color("SupportingWord"), Qt::ForegroundRole);
				item->setFont(timeF);
			}
			else if (colType == col_PrcOther_BuyName || colType == col_PrcOther_SaleName)
			{
				if (m_type == DETAILOTHERTYPE_CFETS && nMsgType == 1)
				{
					std::string stTemp = colType == col_PrcOther_BuyName ? marketInfo.m_body1.m_bid_companyname : marketInfo.m_body1.m_ofr_companyname;
					QString txt, tip;
					BondUtility::setCFETSCompany(em_cfets_best, stTemp, txt, tip);
					item->setData(txt, Qt::DisplayRole);
					item->setData(tip, Qt::ToolTipRole);
                } else if (m_type == DETAILOTHERTYPE_BROKER && colType == col_PrcOther_BuyName) {
                    int nCuBroker = atoi(marketInfo.m_company_id);
                    if (CBrokerList::IsValidBroker(nCuBroker)) {
                        item->setData(nCuBroker, BrokerIdRole);
                    }
                }
			}

			QString strId;
			if (nType == change)
				strId = QString::number(marketInfo.m_indexID);
			else if (atoi(marketInfo.m_body2.m_dealStatus) != 8) //?
				strId = QString::fromLocal8Bit(marketInfo.m_body2.m_id);

			item->setData(strId, DataIdRole);
			m_model->setItem(row, col, item);
		}
	}
}

void DetailQuoteTable::updateDisplayMktStream()
{
	//TODO:考虑线程问题,更改当前的bond
	m_mktStream.clear();
	//TODO: m_lstMktStreamDeal
	auto mktMap = m_type == DETAILOTHERTYPE_CFETS ? m_data->cfetsMarketStream() : m_data->marketStream();//TODO: 加锁?
	std::list<xQBMarketStreamUnit_c> mkts;
	for (auto& m : mktMap)
		mkts.push_back(m.second);

	auto mkdDeal = m_type == DETAILOTHERTYPE_CFETS ? m_data->marketDealCfets() : m_data->marketDeal();
	for (auto& m : mkdDeal)
		mkts.push_back(m.second);
	mkts.sort();

	for (auto iter = mkts.begin(); iter != mkts.end(); ++iter)
	{
		int nMsgType = atoi(iter->m_type);
		int nType = BondUtility::makeTypeOperate(nMsgType, atoi(iter->m_operate));
		bool bContinue{ false };
		switch (m_filterType)
		{
		case data_tkn:
		case data_tkn_match:
		{
			if (nType == change || atoi(iter->m_body2.m_dealStatus) == 8) {
				bContinue = true;
				break;
			}
			if (m_filterType == data_tkn_match) {
				if (iter->m_body2.m_tradeMode[0] != '\0' && iter->m_body2.m_tradeMode[0] != '1') {
					bContinue = true;
					break;
				}
			}
		}
		default:
			break;
		}
		if (bContinue) continue;
		//TODO检查有效性?
		m_mktStream.push_back(*iter);
	}
}

void DetailQuoteTable::initCols()
{
	switch (m_type)
	{
	case DETAILOTHERTYPE_BROKER:
	{
        m_cols << col_PrcOther_State << col_PrcOther_BuyName << col_PrcOther_BuyVol << col_PrcOther_Buy << col_PrcOther_Sale << col_PrcOther_SaleVol << col_PrcOther_Update;
		m_tableSet = new STableColumnSet(m_table, "Detail", this);
		BEGIN_COLUMN;
		ADD_COLUMN(0, m_tableSet, "类型", 0, 40, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");
        ADD_COLUMN(1, m_tableSet, "买方", 0, 60, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");
        ADD_COLUMN(2, m_tableSet, "买量", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
        ADD_COLUMN(3, m_tableSet, "买价", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
        ADD_COLUMN(4, m_tableSet, "卖量", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
        ADD_COLUMN(5, m_tableSet, "卖价", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
        ADD_COLUMN(6, m_tableSet, "时间", 0, 60, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");


        BrokerCorpDelegate* brokerCorpDelegate = new BrokerCorpDelegate(m_table);
        m_table->table()->setItemDelegateForColumn(1, brokerCorpDelegate);

		m_tableSet->setTableWidthFixed(true);
		m_tableSet->apply();
	}
		break;
	case DETAILOTHERTYPE_CFETS:
	{
		m_cols << col_PrcOther_State << col_PrcOther_BuyName << col_PrcOther_BuyVol << col_PrcOther_Buy << col_PrcOther_Sale << col_PrcOther_SaleVol << col_PrcOther_SaleName << col_PrcOther_Update;
		m_tableSet = new STableColumnSet(m_table, "Detail", this);
		BEGIN_COLUMN;
		ADD_COLUMN(0, m_tableSet, "类型", 0, 49, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");
		ADD_COLUMN(1, m_tableSet, "买方", 0, 60, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");
		ADD_COLUMN(2, m_tableSet, "买量", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
		ADD_COLUMN(3, m_tableSet, "买价", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
		ADD_COLUMN(4, m_tableSet, "卖量", 0, -1, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
		ADD_COLUMN(5, m_tableSet, "卖价", 0, 70, 12, 0.25, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kAuto, "");
		ADD_COLUMN(6, m_tableSet, "卖方", 0, 60, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");
		ADD_COLUMN(7, m_tableSet, "时间", 0, 60, 12, -1, false, (Qt::Alignment)(Qt::AlignVCenter | Qt::AlignRight), kFixed, "");

		m_tableSet->setTableWidthFixed(true);
		m_tableSet->apply();
	}
		break;
	case DETAILOTHERTYPE_EXCHANGE:
		break;
	default:
		break;
	}
}

/*void DetailQuoteTable::paintEvent(QPaintEvent* e)
{
	QFrame::paintEvent(e);
	if (m_type != DETAILOTHERTYPE_BROKER)
		return;

	QString strDealNum = tr("今日成交笔数: ");
	if (m_data->bond().IsCrossMarket())
		strDealNum = tr("今日全市场成交笔数: ");

    QString strNum = m_data->titleParams().m_strTransCount;

	QRect r = rect();
	r.adjust(4, 4, 0, 0);
	r.setHeight(24);

	QStylePainter painter(this);
	QFont f = font();
	f.setBold(true);
	f.setPixelSize(13);
	painter.setFont(f);

	painter.drawText(r, strDealNum, QTextOption(Qt::AlignLeft | Qt::AlignVCenter));
	painter.setPen(StyleMgr::instance().color("Highlight"));
	QFontMetrics fm(f);
	int w = fm.horizontalAdvance(strDealNum);
	r.setLeft(r.left() + w);
	painter.drawText(r, strNum, QTextOption(Qt::AlignLeft | Qt::AlignVCenter));
}*/
